import commonFun from './common.js' //公共方法
import store from '@/store/index.js'

function fetch(method, url, data) {
	return new Promise((resolve, reject) => {
		// console.log(commonFun.baseURL + url);
		// console.log('token ' + commonFun.getUserToken());
		//发起请求
		uni.request({
			url: commonFun.baseURL + 'yh/api/' + url,
			data: data,
			method: method,
			header: {
				'content-type': 'application/json', //自定义请求头信息
				'token': commonFun.getUserToken()
			},
			success: (res) => {
				// console.log(res);
				resolve(res.data)
				//用户token失效或用户被禁言等
				if (res.data.code == 501) {
					commonFun.toast(res.data.message);
					commonFun.clearUserInfo();
				}
				//维护中
				if (res.data.code == 505) {
					store.dispatch('setPreserve', true)
				}
			},
			fail: err => {
				reject(err)
			}
		});
	})
}

export default {
	get: function (url, params) {
		return fetch('GET', url, params)
	},
	post: function (url, params) {
		return fetch('POST', url, params)
	},
	delete: function (url, params) {
		return fetch('DELETE', url, params)
	},
	uploadFile(file) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: commonFun.baseURL + 'yh/api/public/upload',
				filePath: file,
				name: 'file',
				header: {
					// 'content-type': 'application/json', //自定义请求头信息
					'token': commonFun.getUserToken()
				},
				success: (res) => {
					resolve(JSON.parse(res.data))
				},
				fail: err => {
					reject(err)
				}
			});
		})
	},
	async uploadFileHasInfo(file) {
		let imageInfo = await commonFun.getLocalImageInfo(file);
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: commonFun.baseURL + 'yh/api/public/upload',
				filePath: file,
				name: 'file',
				header: {
					// 'content-type': 'application/json', //自定义请求头信息
					'token': commonFun.getUserToken()
				},
				success: (res) => {
					let backInfo = JSON.parse(res.data);
					const result = {
						width: imageInfo.data.width,
						height: imageInfo.data.height,
						url: backInfo.result
					}
					backInfo.result = result;
					resolve(backInfo)
				},
				fail: err => {
					reject(err)
				}
			});
		})
	},
	// 上传文件到阿里云
	async uploadFileOSS(fileList) {
		// console.log(fileList);
		let imgList = [];
		return new Promise((resolve, reject) => {
			fileList.forEach(async (li, length) => {
				let imageInfo = await commonFun.getLocalImageInfo(li.path);
				// console.log(li);
				// let suffix = '.png';
				// // #ifdef APP-PLUS
				// let arr_app = imageInfo.data.type.split("/");
				// suffix = arr_app[arr_app.length - 1];
				// // #endif
				// // #ifndef APP-PLUS
				// let arr_h5 = li.type.split("/");
				// suffix = arr_h5[arr_h5.length - 1];
				// // #endif
				// // console.log("suffix:", suffix);
				// const filename = Date.now() + '' + Math.floor(Math.random() * 1000) + '.' + suffix;
				// console.log(filename);
				let imgOss = await this.uploadFile(li.path);
				// console.log(imgOss);
				if (imgOss.code == 200) {
					imgList.push({
						width: imageInfo.data.width,
						height: imageInfo.data.height,
						url: imgOss.result
					});
				}
				if (length + 1 == fileList.length) {
					resolve({
						code: 0,
						msg: '上传成功',
						data: imgList
					});
				}
			})
		})
	},
	// 上传视频到阿里云
	async uploadVideoOSS(file) {
		const resOSS = await this.get('public/getPolicy', {});
		// console.log(resOSS);
		return new Promise(async (resolve, reject) => {
			//发起请求
			const host = resOSS.result.host;
			let suffix = 'mp4';
			// #ifdef APP-PLUS
			let videoInfo = await commonFun.getLocalVideoInfo(file.tempFilePath);
			let arr_app = videoInfo.data.type.split("/");
			suffix = arr_app[arr_app.length - 1];
			// #endif
			// #ifndef APP-PLUS
			let arr_h5 = file.name.split(".");
			suffix = arr_h5[arr_h5.length - 1];
			// #endif
			// console.log("suffix:", suffix);
			const filename = Date.now() + '' + Math.floor(Math.random() * 1000) + '.' + suffix;
			const aliyunFileKey = resOSS.result.dir + filename;
			uni.uploadFile({
				url: host,
				filePath: file.path || file.tempFilePath,
				name: 'file',
				formData: {
					key: aliyunFileKey,
					OSSAccessKeyId: resOSS.result.accessid,
					policy: resOSS.result.policy,
					signature: resOSS.result.signature,
					success_action_status: 200,
				},
				success: function (res) {
					// console.log(res);
					if (res.statusCode == 200) {
						resolve({
							code: 0,
							msg: '上传成功',
							data: {
								url: resOSS.result.url + '/' + aliyunFileKey,
								height: file.height,
								width: file.width,
								size: file.size,
								duration: file.duration,
							}
						});
					} else {
						resolve({
							code: 1,
							msg: '上传失败，请稍后再试'
						});
					}
				},
				fail: function (err) {
					// console.log(err);
					resolve({
						code: 1,
						msg: '上传失败，请稍后再试'
					});
				},
			})
		})
	},
}